<?php
/**
 * D5Power Studio d5power Webgame Engine
 *
 * Extends DOTK system
 * Author: D5Power Studio
 *
 *
 * 第五动力工作室 d5power网页游戏引擎 Ver 1.0
 * 继承自:DOTK引擎
 * 作者：第五动力工作室
 */
 
/** PAGE NOT ALLOWED
 * Verify if user called this page through a allowed page.
 * @message: That file cannot be displayed alone.
 */
if (!isset($allowed_page)) { echo "That file cannot be displayed alone."; exit; }

if (file_exists("lib/config.php")) { require_once("lib/config.php"); }


require_once(CLASS_PATH."MySQLResultSet.class.php");

class d5powerDataAccess extends abstractDataAccess  {
	//TODO: Create a Data Access class to use MySQL.
	
	private static $connected = false;
	
	private $connectid = NULL;
	private static $instance;
	private $nowsql = '';
	
	
	/** Private Constructor for Singleton
	* @no params
	*/
	private function d5powerDataAccess()
	{
		//Nothing for while
	}
	
	public function getInstance()
	{
		if (!isset(self::$instance))
		{
			$class = __CLASS__;
			self::$instance = new $class;
		}
		return self::$instance;
	}
	
	/** Connection function
	* Establishes a connection to Firebird Database.
	* @Static params (defined in config.php)
	*/
	function connect()
	{
		if($this->connected) return;
		$this->connectid = mysql_connect(DB_HOSTNAME,DB_USERNAME,DB_PASSWORD) or die("Can not connect to database.Please check your database setting in config file.");
		mysql_select_db(DB_DATABASE_NAME,$this->connectid) or die("Can not select database,please check your database setting in config file.");
		mysql_query("SET NAMES 'utf8'");
		$this->connected = true;
	}

	/** Disconnect function
	* Disconnect a active link to DB.
	* @no params
	*/
	function disconnect()
	{
		mysql_close($this->connectid);
	}
	
	/** Execute function
	* Executes a prepared query with ibase_prepare
	* @statement - previous prepared query
	* @params - collection of params to be replaced in a prepared query.
	*/
	function execute($query, $params = null)
	{
		try {
			
		  if(count($params) == 0) {
			//$ret = ibase_execute($statement);
			$ret = call_user_func('mysql_query', $query);
		  }
		  else {
			$query = $this->d5powerBuildSQL($query, $params);
			
			$ret = call_user_func_array('mysql_query', $query);
			
			//$ret = ibase_execute($statement, $params);
		  }
		}
		catch(Exception $e) {
		  return 'Error on Mysql execute function: '.$e->getMessage()."\n";
		}
		return $ret;
	}


	/** SendQuery function
	* Evaluates a query text before execute.
	* @query - String containing query text.
	* @params - collection of params to be replaced in query.
	*/
	function & sendQuery($query, $params = null)
	{
		if (!self::$connected) {
		  $this->connect();
		}
	
		if ($this->num_parames($query) != count($params)) {
		  throw new Exception("Input params and query params does not match.");
		  return false;
		}else {
			$this->nowsql = $this->d5powerBuildSQL($query, $params);
			//echo $this->nowsql."<br>";
			$mysql = mysql_query($this->nowsql);

			if (!$this->isError()) {
				$myResultSet = new ResultSet();
		
				$i = 0;
				$array = array();
		
				while($row=@mysql_fetch_array($mysql))
				{
					array_push($array,$row);
				}
				$myResultSet->fetch($array);
			}else {
				$myResultSet = new ResultSet();
				$myResultSet->setError($this->isError());
			}
		}
		return $myResultSet;
	}

	
	function num_parames($query)
	{
		return substr_count($query,'?');
	}
	
	function d5powerBuildSQL($query,$params)
	{
		$sql='';
		$temp = explode('?',$query);
		$i=0;
		foreach($temp as $key=>$value)
		{
			if(empty($value)) continue;
			$sql.= $i==(count($temp)-1) ? $value : $value."'".$params[$key]."'";
			$i++;
		}
		return $sql;
	}
	
	/** isError function
	* Check if the most recent InterBase function call resulted an Error.
	* @params - void.
	*/
	function isError()
	{
		if (mysql_error())
		  return mysql_error()."<br>And your query code is below:<br>---------------------<br>".$this->nowsql;
		else
		  return false;
	}

	
}

?>
